package se.webbzon.boltzmann.textureset;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import se.webbzon.boltzmann.loader.Loader;
import se.webbzon.boltzmann.loader.LoaderException;
import se.webbzon.boltzmann.loader.LoaderUtilityPointer;
import se.webbzon.oschi01.filenameparser.FilenameParser;
import se.webbzon.oschi01.resourceset.ResourceSet;
import se.webbzon.oschi01.resourceset.ResourceSetLoaderException;
import se.webbzon.oschi01.textureset.Texture3D;
import se.webbzon.oschi01.textureset.Texture3DSetLoader;

public class TextureSetLoaderMap implements Loader {

	// A collection of resource names related to this loader
	private final static Collection<String> resourceNames = new ArrayDeque<String>();
		
	static {
		resourceNames.add("textureSet");
	}
	
	// A map containing all loaded texture sets
	private final Map<String,ResourceSet<Texture3D>> content;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new texture set loader which loads the textures into a 
	 * local map. The map can be fetched by calling the method getMap().**/
	public TextureSetLoaderMap() {
		content = new HashMap<String,ResourceSet<Texture3D>>();
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	@Override public String getCategory() {
		return "textureSets";
	}

	@Override public Collection<String> getSupportedResources() {
		return resourceNames;
	}

	@Override public void load(LoaderUtilityPointer pointer, String resourceName,
			Map<String, String> attributeMap) throws LoaderException {
		String name = attributeMap.get("name");
		String expression = attributeMap.get("files");
		Texture3DSetLoader tsl = new Texture3DSetLoader();
		
		Collection<String> filenames = FilenameParser.parse(expression);
		try {
			for (String filename : filenames)
				tsl.addFromURL(new URL(pointer.getXMLURL(),filename));
		} catch (MalformedURLException | ResourceSetLoaderException e) {
			throw new LoaderException(e);
		}
		content.put(name, tsl.getResourceSet());
	}
	
	/** Returns the texture set map associated with this instance. **/
	public Map<String,ResourceSet<Texture3D>> getMap() {
		return Collections.unmodifiableMap(content);
	}

}
